<template>
  <section class="echartBox-wrapper">
    <slot></slot>
    <!--    borderColor: title.direction === 'left' ? '#4193e3' : 'transparent', -->
    <div
      class="title-box"
      :style="{
        textAlign: title.direction ? title.direction : 'center',
        marginLeft: title.direction ? '10px' : '0',
      }"
    >
      <i class="title-tip" v-show="title.direction === 'left'"></i>
      <span class="title-header">{{ title.heading }}</span>
      <span v-if="title.secondary">-{{ title.secondary }}</span>
    </div>

    <a-spin :spinning="loadSpinning" tip="数据加载中..." style="height: 100%">
      <div v-if="echartShow" class="echart-box" :ref="id"></div>
      <a-empty v-else :image="emptyImg" style="color: #fff" />
    </a-spin>
  </section>
</template>
<script>
// import * as Echarts from "echarts";
// import "../echarts/index"
// let echarts = require("echarts/lib/echarts");
import echarts from "../echarts/index";
import { Empty } from "ant-design-vue";
import { mapMutations } from "vuex";
export default {
  props: ["id", "title", "echartsData"],
  data() {
    return {
      loadSpinning: true,
      emptyImg: Empty.PRESENTED_IMAGE_SIMPLE,
      chart: null,
      // echartsData: {
      // dataUnit: null,
      // axisData: [
      //   "通调信息机房",
      //   "中心机房",
      //   "监控机房",
      //   "成都机房",
      //   "财务部机房",
      //   "licy测试机房",
      // ],
      // seriesData: [
      //   { type: "紧急", data: ["3", "6", "10", "15", "18", "24"] },
      //   { type: "严重", data: ["1", "4", "6", "7", "10", "15"] },
      //   { type: "一般", data: ["4", "7", "8", "12", "16", "22"] },
      //   { type: "预警", data: ["2", "5", "6.7", "9", "12", "18"] },
      // ],
      // },
      seriesData: [],
      echartShow: true,
      unit: "%",
    };
  },
  watch: {
    // 监听echartsData变化
    echartsData: {
      handler(newVal) {
        if (newVal) {
          if (this.echartsData) {
            if (this.echartsData.seriesData===undefined) {
              this.loadSpinning = false;
              this.echartShow = false;
            }
            if (this.echartsData.seriesData.length > 0) {
              this.echartShow = true;
              this.initData(this.echartsData.seriesData);
              this.$nextTick(() => {
                this.loadSpinning = false;
                this.renderEchart();
              });
            } else {
              this.loadSpinning = false;
              this.echartShow = false;
            }
          }
        }
      },
      deep: true,
      // immediate: true,
    },
  },
  created() {},
  methods: {
    ...mapMutations("echartConfig", ["SET_DATAZOOMVAL"]),
    initData(seriesData) {
      console.log("seriesData:----", seriesData);
      // if (seriesData && seriesData.length > 0) {
      //   seriesData.forEach((item) => {
      //     this.seriesData.push({
      //       name: item.name,
      //       data: item.data,
      //       type: "line",
      //       smooth: true,
      //       showSymbol: false,
      //     });
      //   });
      // }

      // item.data.map(it=>{return it+(this.echartsData.dataUnit?this.echartsData.dataUnit:item.unit)})
      if (seriesData) {
        return seriesData.map((item) => {
          console.log(item.unit);
          let obj = {
            unit: item.unit,
            name: item.name,
            data: item.data,
            type: "line",
            smooth: true,
            showSymbol: false,
          };
          // 渐变色
          if (item.lineGradient) {
            obj.areaStyle = {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: item.gradientColor[0],
                },
                {
                  offset: 1,
                  color: item.gradientColor[1],
                },
              ]),
            };
          }
          return obj;
        });
      }
    },
    renderEchart() {
      //2.初始化
      const linechart = echarts.init(this.$refs[this.id]);
      //3.配置数据
      let option = {
        dataZoom: [
          {
            type: "inside",
            throttle: "50",
            minValueSpan: 4,
            start: 1,
            // end: 50,
            zoomLock: true,
          },
        ],
        // title: {
        //   text: this.title,
        //   x: "center",
        //   y: "10",
        //   textStyle: {
        //     color: "#48A3F9",
        //   },
        // },

        tooltip: {
          //鼠标悬浮时设置
          trigger: "axis",
          backgroundColor: "rgba(25,62,119,0.4)",
          borderColor: "#4372B9",
          textStyle: {
            color: "#fff",
          },
          formatter: (params) => {
            let res = "",
              axisValueLabel = "";
            params.forEach((item) => {
              axisValueLabel = item.axisValue;
              res += `<li>
               ${item.marker} ${item.seriesName} ${item.value} ${
                this.echartsData.dataUnit
                  ? this.echartsData.dataUnit
                  : this.echartsData.seriesData.filter(
                      (it) => it.name === item.seriesName
                    )[0].unit
              }</li>`;
            });
            return `<div>${axisValueLabel}</div>
              <ul>${res}</ul>`;
          },
        },
        legend: {
          data:
            this.echartsData.seriesData &&
            this.echartsData.seriesData.map((item) => item.name),
          orient:
            (this.echartsData.legend && this.echartsData.legend.orient) ||
            "horizontal",
          right:
            (this.echartsData.legend && this.echartsData.legend.right) || 10,
          top: (this.echartsData.legend && this.echartsData.legend.top) || 10,
          itemWidth: 10,
          itemHeight: 0,
          itemGap: 4,
          textStyle: {
            color: "#fff",
            fontSize: 10,
          },
        },
        grid: {
          left: "2%",
          right: "2%",
          bottom: "20",
          top: 30,
          containLabel: true,
        },

        color: this.echartsData.color || [],
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.echartsData.axisData,
          axisLine: {
            show: true,
            lineStyle: {
              color: "#4F73A",
              type: "solid",
            },
          },
          axisLabel: {
            // x轴的文字设置
            interval: this.echartsData.interval || 0,
            rotate: this.echartsData.rotate || 0,
            textStyle: {
              color: "#fff",
            },
            formatter: (value) => {
              if (this.echartsData.formatter) {
                const timeVals = value.split(" ")[1].split(":", 2);
                return `${timeVals[0]}:${timeVals[1]}`;
              } else {
                return value;
              }
            },
          },

          splitLine: {
            show: true, //想要不显示网格线，改为false
            lineStyle: {
              color: ["#20355D"],
            },
          },
        },
        yAxis: {
          type: "value",
          axisLine: {
            show: true,
            lineStyle: {
              color: "#4F73A5",
              type: "solid",
            },
          },
          axisLabel: {
            textStyle: {
              color: "#fff",
            },
          },
          splitLine: {
            show: true, //想要不显示网格线，改为false
            lineStyle: {
              color: ["#20355D"],
            },
          },
        },
        series: this.initData(this.echartsData.seriesData),
        // series: this.seriesData,
      };

      // 4.传入数据
      linechart.clear();
      linechart.setOption(option);
      linechart.on("datazoom", (e) => {
        this.SET_DATAZOOMVAL(e.batch[0].end);
      });
      // 自动调节echarts的大小
      window.addEventListener("resize", () => {
        linechart.resize();
      });
      // 销毁调节echarts的大小
      this.$on("hook:destroyed", () => {
        window.removeEventListener("resize", () => {
          linechart.resize();
        });
      });
    },
  },
};
</script>
<style lang="scss">
$titleHeight: 20px;
$titleMargin: 6px;
.echartBox-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  .title-box {
    height: $titleHeight;
    line-height: $titleHeight;
    margin: $titleMargin 0;
    font-size: 16px;
    font-weight: bold;
    color: #4193e3;
    margin-left: 10px;
    .title-tip {
      display: inline-block;
      width: 3px;
      height: 20px;
      background: #4193e3;
      vertical-align: middle;
      margin-right: 10px;
    }
  }
  .ant-spin-container {
    height: 100%;
    .echart-box {
      height: calc(100% - #{$titleHeight} - 2 * #{$titleMargin});
      width: 100%;
    }
  }
}
</style>
